﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using KenLib.Dal;
using KenLib.BusinessManager;
using DataInfo.BusinessManager;
using KenLib.BusinessObject;
using DataInfo;
using System.Text.RegularExpressions;

public partial class Org_frmO_EmpContractTypeInput : System.Web.UI.Page
{
    protected void Page_PreRender(object sender, EventArgs e)
    {
        ViewState["CountingSubmitOrg40"] = Session["CountingSubmitOrg40"];
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ((Org_MasterPage)this.Master).changeTitle("雇用情報登録");
        ((Org_MasterPage)this.Master).HideLiArea("frmO_EmpContractTypeInput");

        
        //if (Session["社員ID"] == null || Session["社員ID"] == "" || Session["社員ID"].ToString() == "")
        //    Response.Redirect("frmO_EmpEnterInput.aspx");

        if (!Page.IsPostBack)
        {
            LoadData();
            ClearTextPage();
            LoadMessageValid();
            Session["CountingSubmitOrg40"] = Server.UrlEncode(System.DateTime.Now.ToString());
            //Session["UrlRequestToOrg40"] = Request.UrlReferrer.ToString();
            ViewState["IdCurrentOrg40"] = "";
            ViewState["IdCurrentOutputOrg40Update"] = "";
            ViewState["IdCurrentOutputOrg40"] = "";
            ViewState["TableUpdateOrg40"] = null;
            ViewState["TableInsertOrg40"] = null;
            ViewState["indexPageOrg40"] = 0;
            ViewState["FirstRowUpdateOrg40"] = true;

            if (Request.QueryString["id"] != null && Request.QueryString["id2"] == null && (Request.QueryString["id3"] == null || Request.QueryString["id3"] != null))
            {
                
                // Kiem tra param truyen den co hop le
                int _社員ID;
                Int32.TryParse(Request.QueryString["id"].ToString(), out _社員ID);
                if (_社員ID != 0)
                {
                    // Hien thi GridView rong
                    string header = "ID,雇用区分,発令開始日,実際開始日";
                    string phraseEmpty = "データーがありません。";
                    btn_次.Enabled = false;
                    //ShowGridViewNotClassEmpty(grv_human, header, phraseEmpty);
                    ShowDataPageFirstLoadInsertMode(_社員ID.ToString());
                    
                    Session["PageCurrentOrg39Mode"] = "1";   
                }
                
            }
            else if (Request.QueryString["id"] != null && Request.QueryString["id2"] != null && Request.QueryString["id3"] == null)
            {
                Session["PageCurrentOrg39Mode"] = "2";
                int _社員ID;
                Int32.TryParse(Request.QueryString["id"].ToString(), out _社員ID);
                string _ID = Request.QueryString["id2"].ToString();

                ShowDataPageFirstLoadUpdateMode(_社員ID.ToString(), _ID);
                ShowDataPageLoadUpdateMode(_社員ID.ToString());
                btn_次.Enabled = false;
                btn登録.Text = "更新";
               
            }
            else if (Request.QueryString["id"] == null && Request.QueryString["id2"] == null && Request.QueryString["id3"] == null)
            {
                Session["PageCurrentOrg39Mode"] = "3";
                string _社員ID = Session["社員ID"].ToString();
                ShowDataPageFirstLoadInsertMode(_社員ID.ToString());
            }
            else if (Request.QueryString["id"] != null && Request.QueryString["id2"] != null && Request.QueryString["id3"] != null)
            {
                Session["PageCurrentOrg39Mode"] = "4";
                int _社員ID;
                Int32.TryParse(Request.QueryString["id"].ToString(), out _社員ID);
                string _ID = Request.QueryString["id2"].ToString();

                ShowDataPageFirstLoadUpdateMode(_社員ID.ToString(), _ID);
                ShowDataPageLoadUpdateMode(_社員ID.ToString());
                btn_次.Enabled = false;
                btn登録.Text = "更新";

            }
        }
    }

    /// <summary>
    /// Hien thi du lieu vao GridView khi o che do Insert
    /// </summary>
    /// <param name="_社員ID"></param>
    protected void ShowDataPageFirstLoadInsertMode(string _社員ID)
    {
        雇用情報Manager _manager = new 雇用情報Manager();
        DataTable dt = _manager.ShowDataPageLoadFirstInsertMode(_社員ID);
        if (dt.Rows.Count > 0)
        {
            grv_human.DataSource = dt;
            grv_human.DataBind();
            ViewState["TableInsertOrg40"] = dt;
        }
        else
        {
            // Hien thi GridView rong
            string header = "ID,雇用区分,発令開始日,実際開始日";
            string phraseEmpty = "データーがありません。";
            ShowGridViewNotClassEmpty(grv_human, header, phraseEmpty);
        }
    }

    protected void ShowDataPageLoadUpdateMode(string _社員ID)
    {
        雇用情報Manager _manager = new 雇用情報Manager();
        DataTable dt = _manager.ShowDataPageLoadFirstInsertMode(_社員ID);
        if (dt.Rows.Count > 0)
        {
            grv_human.DataSource = dt;
            grv_human.DataBind();
            ViewState["TableUpdateOrg40"] = dt;
        }
        else
        {
            // Hien thi GridView rong
            string header = "ID,雇用区分,発令開始日,実際開始日";
            string phraseEmpty = "データーがありません。";
            ShowGridViewNotClassEmpty(grv_human, header, phraseEmpty);
        }
    }

    protected void ShowDataPageFirstLoadUpdateMode(string _社員ID, string _ID)
    {
        雇用情報Manager _manager = new 雇用情報Manager();
        DataTable dt = _manager.ShowDataPageLoadFirstUpdateMode(_社員ID, _ID);
        if (dt.Rows.Count > 0)
        {
            try
            {

                string temp1 = dt.Rows[0]["雇用区分"].ToString();
                string temp2 = dt.Rows[0]["発令開始日"].ToString();
                string temp3 = dt.Rows[0]["実際開始日"].ToString();

                if (temp1 != "")
                {
                    ListItem lst = ddl_雇用区分.Items.FindByValue(temp1);
                    ddl_雇用区分.SelectedIndex = ddl_雇用区分.Items.IndexOf(lst);
                }

                if (temp3 != "")
                {
                    txt_実際開始日.Text = temp3.Substring(0, 10);
                }

                if (temp2 != "")
                {
                    txt_発令開始日.Text = temp2.Substring(0, 10);
                }
            }
            catch (Exception ex) { }
        }
        else
        {
            // Hien thi GridView rong
            string header = "ID,雇用区分,発令開始日,実際開始日";
            string phraseEmpty = "データーがありません。";
            ShowGridViewNotClassEmpty(grv_human, header, phraseEmpty);
        }
    }

    private void LoadMessageValid()
    {
        RegularExpressionValidator1.ErrorMessage = GetError("ER00002");
        RegularExpressionValidator2.ErrorMessage = GetError("ER00002");
        CustomValidator1.ErrorMessage = GetError("ER00005");
        CustomValidator2.ErrorMessage = GetError("ER00001");
    }

    /// <summary>
    /// Coder: Load thong tin cho gridview
    /// </summary>
    private void LoadData()
    {
        ddl_雇用区分.DataSource = new 雇用区分Manager().SelectPartial();

        ddl_雇用区分.DataTextField = "雇用区分名";
        ddl_雇用区分.DataValueField = "雇用区分_s";
        ddl_雇用区分.DataBind();
        ListItem lstTem = new ListItem();
        lstTem.Text = "[選択]";
        lstTem.Value = "-11";
        lstTem.Selected = true;
        ddl_雇用区分.Items.Insert(0, lstTem);

    }

    protected void btn_次_Click(object sender, EventArgs e)
    {
        string id = Request.QueryString["id"] != null ? Request.QueryString["id"].ToString() : "";
        if (id != "")
            Response.Redirect("frmO_EmpDegreeByCompInput.aspx?id=" + id);
        else
            Response.Redirect("frmO_EmpDegreeByCompInput.aspx");
    }

    protected void btn_戻る_Click(object sender, EventArgs e)
    {
         string PageCurrentMode = Session["PageCurrentOrg39Mode"] != null ? Session["PageCurrentOrg39Mode"].ToString() : "";

         if (PageCurrentMode == "1")
         {
             //Response.Redirect("frmO_EmpEnterInput.aspx?id=" + Request.QueryString["id"].ToString()); 
             Response.Redirect("frmO_EmpBasicInfo.aspx?id=" + Request.QueryString["id"].ToString()); 
         }

         if (PageCurrentMode == "2")
         {
             Response.Redirect("frmO_EmpBasicInfo.aspx?id=" + Request.QueryString["id"].ToString() + "&id2=" + Request.QueryString["id2"].ToString());
         }

         if (PageCurrentMode == "3")
         {
             Response.Redirect("frmO_EmpEnterInput.aspx");
         }

         if (PageCurrentMode == "4")
         {
             Response.Redirect("frmO_EmpBasicInfo.aspx?id=" + Request.QueryString["id"].ToString() + "&id2=" + Request.QueryString["id2"].ToString() + "&id3=" + Request.QueryString["id3"].ToString());
         }
        
    }

    protected void btnリセット_Click(object sender, EventArgs e)
    {
        // ClearTextPage();
        HienThiTrangThaiMacDinh();
    }

    private void HienThiTrangThaiMacDinh()
    {
        string PageCurrentMode = Session["PageCurrentOrg39Mode"] != null ? Session["PageCurrentOrg39Mode"].ToString() : "";

        if (PageCurrentMode == "1")
        {
            string IdCurrent = ViewState["IdCurrentOrg40"] != null ? ViewState["IdCurrentOrg40"].ToString() : "";
            if (IdCurrent != "")
            {
                int index = Int32.Parse(ViewState["indexOrg40"].ToString());
                DataTable dt = (DataTable)ViewState["TableInsertOrg40"];
                if (dt != null && dt.Rows.Count > 0)
                {
                    string temp1 = dt.Rows[index]["雇用区分"].ToString();
                    string temp2 = dt.Rows[index]["発令開始日"].ToString();
                    string temp3 = dt.Rows[index]["実際開始日"].ToString();
                    if (temp1 != "")
                    {
                        ListItem lst = ddl_雇用区分.Items.FindByValue(temp1);
                        ddl_雇用区分.SelectedIndex = ddl_雇用区分.Items.IndexOf(lst);
                    }

                    if (temp3 != "")
                    {
                        txt_実際開始日.Text = temp3.Substring(0, 10);
                    }

                    if (temp2 != "")
                    {
                        txt_発令開始日.Text = temp2.Substring(0, 10);
                    }
                }
            }
            else if (IdCurrent == "")
            {
                ClearTextPage();
                string _社員ID = Request.QueryString["id"].ToString();
                ShowDataPageFirstLoadInsertMode(_社員ID.ToString());
            }
        }

        if (PageCurrentMode == "3")
        {
            string IdCurrent = ViewState["IdCurrentOrg40"] != null ? ViewState["IdCurrentOrg40"].ToString() : "";
            if (IdCurrent != "")
            {
                int index = Int32.Parse(ViewState["indexOrg40"].ToString());
                DataTable dt = (DataTable)ViewState["TableInsertOrg40"];
                if (dt != null && dt.Rows.Count > 0)
                {
                    string temp1 = dt.Rows[index]["雇用区分"].ToString();
                    string temp2 = dt.Rows[index]["発令開始日"].ToString();
                    string temp3 = dt.Rows[index]["実際開始日"].ToString();
                    if (temp1 != "")
                    {
                        ListItem lst = ddl_雇用区分.Items.FindByValue(temp1);
                        ddl_雇用区分.SelectedIndex = ddl_雇用区分.Items.IndexOf(lst);
                    }

                    if (temp3 != "")
                    {
                        txt_実際開始日.Text = temp3.Substring(0, 10);
                    }

                    if (temp2 != "")
                    {
                        txt_発令開始日.Text = temp2.Substring(0, 10);
                    }
                }
            }
            else if (IdCurrent == "")
            {
                ClearTextPage();
                string _社員ID = Session["社員ID"].ToString();
                ShowDataPageFirstLoadInsertMode(_社員ID.ToString());
            }
        }

        if (PageCurrentMode == "2")
        {
            string IdCurrent = ViewState["IdCurrentOrg40"] != null ? ViewState["IdCurrentOrg40"].ToString() : "";
            if (IdCurrent != "")
            {
                int index = Int32.Parse(ViewState["indexOrg40"].ToString());
                DataTable dt = (DataTable)ViewState["TableUpdateOrg40"];
                if (dt != null && dt.Rows.Count > 0)
                {
                    string temp1 = dt.Rows[index]["雇用区分"].ToString();
                    string temp2 = dt.Rows[index]["発令開始日"].ToString();
                    string temp3 = dt.Rows[index]["実際開始日"].ToString();
                    if (temp1 != "")
                    {
                        ListItem lst = ddl_雇用区分.Items.FindByValue(temp1);
                        ddl_雇用区分.SelectedIndex = ddl_雇用区分.Items.IndexOf(lst);
                    }

                    if (temp3 != "")
                    {
                        txt_実際開始日.Text = temp3.Substring(0, 10);
                    }

                    if (temp2 != "")
                    {
                        txt_発令開始日.Text = temp2.Substring(0, 10);
                    }
                }
            }
            else if (IdCurrent == "")
            {
                bool check = ViewState["FirstRowUpdateOrg40"] != null ? (bool)ViewState["FirstRowUpdateOrg40"] : false;
                if (check)
                {
                    string _社員ID = Request.QueryString["id"].ToString();
                    string _ID = Request.QueryString["id2"].ToString();
                    ShowDataPageFirstLoadUpdateMode(_社員ID.ToString(), _ID);
                }
                else
                {
                    ClearTextPage();
                    string _社員ID = Request.QueryString["id"].ToString();
                    string _ID = Request.QueryString["id2"].ToString();
                    ShowDataPageLoadUpdateMode(_社員ID.ToString());
                }
            }
        }

        if (PageCurrentMode == "4")
        {
            string IdCurrent = ViewState["IdCurrentOrg40"] != null ? ViewState["IdCurrentOrg40"].ToString() : "";
            if (IdCurrent != "")
            {
                int index = Int32.Parse(ViewState["indexOrg40"].ToString());
                DataTable dt = (DataTable)ViewState["TableUpdateOrg40"];
                if (dt != null && dt.Rows.Count > 0)
                {
                    string temp1 = dt.Rows[index]["雇用区分"].ToString();
                    string temp2 = dt.Rows[index]["発令開始日"].ToString();
                    string temp3 = dt.Rows[index]["実際開始日"].ToString();
                    if (temp1 != "")
                    {
                        ListItem lst = ddl_雇用区分.Items.FindByValue(temp1);
                        ddl_雇用区分.SelectedIndex = ddl_雇用区分.Items.IndexOf(lst);
                    }

                    if (temp3 != "")
                    {
                        txt_実際開始日.Text = temp3.Substring(0, 10);
                    }

                    if (temp2 != "")
                    {
                        txt_発令開始日.Text = temp2.Substring(0, 10);
                    }
                }
            }
            else if (IdCurrent == "")
            {
                bool check = ViewState["FirstRowUpdateOrg40"] != null ? (bool)ViewState["FirstRowUpdateOrg40"] : false;
                if (check)
                {
                    string _社員ID = Request.QueryString["id"].ToString();
                    string _ID = Request.QueryString["id2"].ToString();
                    ShowDataPageFirstLoadUpdateMode(_社員ID.ToString(), _ID);
                }
                else
                {
                    ClearTextPage();
                    string _社員ID = Request.QueryString["id"].ToString();
                    string _ID = Request.QueryString["id2"].ToString();
                    ShowDataPageLoadUpdateMode(_社員ID.ToString());
                }
            }
        }
    }

    /// <summary>
    /// Lam sach text page
    /// </summary>
    private void ClearTextPage()
    {
        try
        {
            txt_発令開始日.Text = "";
            txt_実際開始日.Text = "";
            ddl_雇用区分.Focus();
            ddl_雇用区分.SelectedIndex = 0;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    /// <summary>
    /// alert() thong diep
    /// </summary>
    private void ErrorValid()
    {
        String str;
        str = "<script type='text/javascript'>";
        str += "alert('" + GetError("ER00002") + "')";
        str += "</script>";
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "err", str, false);
    }

    /// <summary>
    /// Lay thong tin loi ung voi ma loi
    /// </summary>
    /// <param name="errorid"></param>
    /// <returns></returns>
    public string GetError(string errorid)
    {
        Error er = new Error();
        er.ErrorID = errorid;
        ErrorManager frm_error = new ErrorManager();
        DataTable dt = frm_error.getError(er);
        return dt.Rows[0][2].ToString();
    }

    /// <summary>
    /// Kiem tra ngay thang nhap vao co hop le khong
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    protected Boolean checkDateValid(String input)
    {
        String pattern = @"^(?ni:(?=\d)((?'year'((1[6-9])|([2-9]\d))\d\d)(?'sep'[/.-])(?'month'0?[1-9]|1[012])\2(?'day'((?<!(\2((0?[2469])|11)\2))31)|(?<!\2(0?2)\2)(29|30)|((?<=((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00)\2\3\2)29)|((0?[1-9])|(1\d)|(2[0-8])))(?:(?=\x20\d)\x20|$))?((?<time>((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2}))?)$";
        return Regex.IsMatch(input, pattern);
    }

    protected void btn登録_Click(object sender, EventArgs e)
    {
        if(ddl_雇用区分.SelectedValue.ToString() == "-11" && txt_発令開始日.Text == "" &&  txt_実際開始日.Text == "")
        {
            ClearTextPage();
            HienThiTrangThaiMacDinh();
            return;
        }

        雇用情報Manager _manager = new 雇用情報Manager();
        雇用情報 obj = new 雇用情報();

        obj.廃止区分 = 0;
        if (ddl_雇用区分.SelectedValue.ToString() != "-11")
        {
            obj.雇用区分_1 = ddl_雇用区分.SelectedValue.ToString();
            obj.雇用区分名_1 = ddl_雇用区分.SelectedItem.Text.ToString();
        }
        if (txt_発令開始日.Text != "")
        {
            DateTime d1 = DateTime.Parse(txt_発令開始日.Text);
            obj.発令開始日_1 = d1;
        }
        
        if (txt_実際開始日.Text != "")
        {
            DateTime d2 = DateTime.Parse(txt_実際開始日.Text);
            obj.実際開始日_1 = d2;
        }
        
        if (Request.QueryString["id"] != null && Request.QueryString["id2"] == null)
        {
            string _社員ID = Request.QueryString["id"].ToString();
            obj.社員ID = Int32.Parse(_社員ID);
        }
        else if (Request.QueryString["id"] != null && Request.QueryString["id2"] != null)
        {
            string _社員ID = Request.QueryString["id"].ToString();
            obj.社員ID = Int32.Parse(_社員ID);
            string _ID = Request.QueryString["id2"].ToString();
            obj.ID = Int32.Parse(_ID);
        }
        else if (Request.QueryString["id"] == null && Request.QueryString["id2"] == null)
        {
            string _社員ID = Session["社員ID"].ToString();
            obj.社員ID = Int32.Parse(_社員ID);
        }

        // Xet dang o mode nao de xu ly viec Insert va Update cho dung
        string PageCurrentMode = Session["PageCurrentOrg39Mode"] != null ? Session["PageCurrentOrg39Mode"].ToString() : "";
        
        if (PageCurrentMode == "1")
        {
            // Day la truong hop thuoc che do Insert
            string IdCurrent = ViewState["IdCurrentOrg40"] != null ? ViewState["IdCurrentOrg40"].ToString() : "";
            if (IdCurrent == "")
            {
                if (ViewState["CountingSubmitOrg40"].ToString() == Session["CountingSubmitOrg40"].ToString())
                {
                    // Truong hop insert moi hoan toan
                    int kq = 0;
                    bool checkSame = false;
                    checkSame = _manager.CheckSameOrg40(obj);
                    if (checkSame == false)
                    {
                        int intIdCurrent = 0;
                        kq = _manager.InsertDataOrg40(obj, out intIdCurrent);
                        if (kq != 0 && intIdCurrent != 0)
                        {
                            ViewState["IdCurrentOrg40"] = "";
                            ViewState["IdCurrentOutputOrg40"] = intIdCurrent.ToString();
                            ClearTextPage();
                            ShowDataPageFirstLoadInsertMode(obj.社員ID.ToString());
                            Session["CountingSubmitOrg40"] = Server.UrlEncode(System.DateTime.Now.ToString());

                        }
                    }
                    else
                    {
                        string MessageCode = GetError("ER00009");
                        //ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('" + MessageCode + "');</script>");
                        //return;
                        Page.ClientScript.RegisterStartupScript(Page.GetType(), "Same 2", "alert('" + MessageCode + "');", true);
                    }
                }
                else
                {
                    ClearTextPage();
                    ShowDataPageFirstLoadInsertMode(obj.社員ID.ToString());
                }
            }
            else if (IdCurrent != "")
            {
                // Truong hop cap nhat lai dong tuong ung
                int kq = 0;
                bool checkExist = false;
                obj.ID = Int32.Parse(IdCurrent);
                
                checkExist = _manager.CheckExistsOrg40(obj);

                if (checkExist == true)
                {
                    kq = _manager.UpdateDateOrg39BaseCurrentID(obj);
                    if (kq != 0 && kq != -1)
                    {
                        ViewState["IdCurrentOrg40"] = "";
                        ViewState["IdCurrentOutputOrg40Update"] = IdCurrent;
                        btn登録.Text = "登録";
                        ClearTextPage();
                        ShowDataPageFirstLoadInsertMode(obj.社員ID.ToString());
                        
                    }
                }
                else
                {
                    bool checkSame = false;
                    checkSame = _manager.CheckSameOrg40(obj);
                    if (checkSame == false)
                    {
                         kq = _manager.UpdateDateOrg39BaseCurrentID(obj);
                         if (kq != 0 && kq != -1)
                         {
                             ViewState["IdCurrentOrg40"] = "";
                             ViewState["IdCurrentOutputOrg40Update"] = IdCurrent;
                             btn登録.Text = "登録";
                             ClearTextPage();
                             ShowDataPageFirstLoadInsertMode(obj.社員ID.ToString());
                         }
                    }
                    else
                    {
                        string MessageCode = GetError("ER00009");
                        Page.ClientScript.RegisterStartupScript(typeof(Page), "Same 2", "alert('" + MessageCode + "');", true);
                    }
                }
            }
        }


        if (PageCurrentMode == "2")
        {
            // Day la truong hop thuoc che do Update
            string IdCurrent = ViewState["IdCurrentOrg40"] != null ? ViewState["IdCurrentOrg40"].ToString() : "";
            if (IdCurrent == "")
            {
                //Update lai dong dau tien
                IdCurrent = obj.ID.ToString();
                // Truong hop cap nhat lai dong tuong ung
                int kq = 0;
                bool checkExist = false;
              
                checkExist = _manager.CheckExistsOrg40(obj);

                if (checkExist == true)
                {
                    kq = _manager.UpdateDateOrg39BaseCurrentID(obj);
                    if (kq != 0 && kq != -1)
                    {
                        btn登録.Text = "登録";
                        ClearTextPage();
                        ShowDataPageLoadUpdateMode(obj.社員ID.ToString());
                        ViewState["IdCurrentOrg40"] = "";
                        ViewState["IdCurrentOutputOrg40Update"] = IdCurrent;
                        ViewState["FirstRowUpdateOrg40"] = false;
                    }
                }
                else
                {
                    bool checkSame = false;
                    checkSame = _manager.CheckSameOrg40(obj);
                    if (checkSame == false)
                    {
                        kq = _manager.UpdateDateOrg39BaseCurrentID(obj);
                        if (kq != 0 && kq != -1)
                        {
                            btn登録.Text = "登録";
                            ClearTextPage();
                            ShowDataPageLoadUpdateMode(obj.社員ID.ToString());
                            ViewState["IdCurrentOrg40"] = "";
                            ViewState["IdCurrentOutputOrg40Update"] = IdCurrent;
                            ViewState["FirstRowUpdateOrg40"] = false;
                        }
                    }
                    else
                    {
                        string MessageCode = GetError("ER00009");
                        Page.ClientScript.RegisterStartupScript(typeof(Page), "Same 2", "alert('" + MessageCode + "');", true);
                    }
                }
            }

            if (IdCurrent != "")
            {
                // Truong hop cap nhat lai dong tuong ung
                int kq = 0;
                bool checkExist = false;
                obj.ID = Int32.Parse(IdCurrent);

                checkExist = _manager.CheckExistsOrg40(obj);

                if (checkExist == true)
                {
                    kq = _manager.UpdateDateOrg39BaseCurrentID(obj);
                    if (kq != 0 && kq != -1)
                    {
                        btn登録.Text = "登録";
                        ClearTextPage();
                        ShowDataPageLoadUpdateMode(obj.社員ID.ToString());
                        ViewState["IdCurrentOrg40"] = "";
                        ViewState["IdCurrentOutputOrg40Update"] = IdCurrent;
                    }
                }
                else
                {
                    bool checkSame = false;
                    checkSame = _manager.CheckSameOrg40(obj);
                    if (checkSame == false)
                    {
                        kq = _manager.UpdateDateOrg39BaseCurrentID(obj);
                        if (kq != 0 && kq != -1)
                        {
                            btn登録.Text = "登録";
                            ClearTextPage();
                            ShowDataPageLoadUpdateMode(obj.社員ID.ToString());
                            ViewState["IdCurrentOrg40"] = "";
                            ViewState["IdCurrentOutputOrg40Update"] = IdCurrent;
                        }
                    }
                    else
                    {
                        string MessageCode = GetError("ER00009");
                        Page.ClientScript.RegisterStartupScript(typeof(Page), "Same 2", "alert('" + MessageCode + "');", true);
                    }
                }
            }
        }


        if (PageCurrentMode == "3")
        {
            // Day la truong hop thuoc che do Insert
            string IdCurrent = ViewState["IdCurrentOrg40"] != null ? ViewState["IdCurrentOrg40"].ToString() : "";
            if (IdCurrent == "")
            {
                if (ViewState["CountingSubmitOrg40"].ToString() == Session["CountingSubmitOrg40"].ToString())
                {
                    // Truong hop insert moi hoan toan
                    int kq = 0;
                    bool checkSame = false;
                    checkSame = _manager.CheckSameOrg40(obj);
                    if (checkSame == false)
                    {
                        int intIdCurrent = 0;
                        kq = _manager.InsertDataOrg40(obj, out intIdCurrent);
                        if (kq != 0 && intIdCurrent != 0)
                        {
                            ViewState["IdCurrentOrg40"] = "";
                            ViewState["IdCurrentOutputOrg40"] = intIdCurrent.ToString();
                            ClearTextPage();
                            ShowDataPageFirstLoadInsertMode(obj.社員ID.ToString());
                            Session["CountingSubmitOrg40"] = Server.UrlEncode(System.DateTime.Now.ToString());

                        }
                    }
                    else
                    {
                        string MessageCode = GetError("ER00009");
                        //ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('" + MessageCode + "');</script>");
                        //return;
                        Page.ClientScript.RegisterStartupScript(Page.GetType(), "Same 2", "alert('" + MessageCode + "');", true);
                    }
                }
                else
                {
                    ClearTextPage();
                    ShowDataPageFirstLoadInsertMode(obj.社員ID.ToString());
                }
            }
            else if (IdCurrent != "")
            {
                // Truong hop cap nhat lai dong tuong ung
                int kq = 0;
                bool checkExist = false;
                obj.ID = Int32.Parse(IdCurrent);

                checkExist = _manager.CheckExistsOrg40(obj);

                if (checkExist == true)
                {
                    kq = _manager.UpdateDateOrg39BaseCurrentID(obj);
                    if (kq != 0 && kq != -1)
                    {
                        ViewState["IdCurrentOrg40"] = "";
                        ViewState["IdCurrentOutputOrg40Update"] = IdCurrent;
                        btn登録.Text = "登録";
                        ClearTextPage();
                        ShowDataPageFirstLoadInsertMode(obj.社員ID.ToString());

                    }
                }
                else
                {
                    bool checkSame = false;
                    checkSame = _manager.CheckSameOrg40(obj);
                    if (checkSame == false)
                    {
                        kq = _manager.UpdateDateOrg39BaseCurrentID(obj);
                        if (kq != 0 && kq != -1)
                        {
                            ViewState["IdCurrentOrg40"] = "";
                            ViewState["IdCurrentOutputOrg40Update"] = IdCurrent;
                            btn登録.Text = "登録";
                            ClearTextPage();
                            ShowDataPageFirstLoadInsertMode(obj.社員ID.ToString());
                        }
                    }
                    else
                    {
                        string MessageCode = GetError("ER00009");
                        Page.ClientScript.RegisterStartupScript(typeof(Page), "Same 2", "alert('" + MessageCode + "');", true);
                    }
                }
            }
        }


        if (PageCurrentMode == "4")
        {
            // Day la truong hop thuoc che do Update
            string IdCurrent = ViewState["IdCurrentOrg40"] != null ? ViewState["IdCurrentOrg40"].ToString() : "";

            if (IdCurrent == "")
            {
                string boolFirstRowUpdate = ViewState["FirstRowUpdateOrg40"] != null ? ViewState["FirstRowUpdateOrg40"].ToString() : "false";
                //Update lai dong dau tien
                if (boolFirstRowUpdate == "True" || boolFirstRowUpdate == "true")
                {
                    IdCurrent = obj.ID.ToString();
                    // Truong hop cap nhat lai dong tuong ung
                    int kq = 0;
                    bool checkExist = false;

                    checkExist = _manager.CheckExistsOrg40(obj);

                    if (checkExist == true)
                    {
                        kq = _manager.UpdateDateOrg39BaseCurrentID(obj);
                        if (kq != 0 && kq != -1)
                        {
                            btn登録.Text = "登録";
                            ClearTextPage();
                            ShowDataPageLoadUpdateMode(obj.社員ID.ToString());
                            ViewState["IdCurrentOrg40"] = "";
                            ViewState["IdCurrentOutputOrg40Update"] = IdCurrent;
                            ViewState["FirstRowUpdateOrg40"] = false;
                        }
                    }
                    else
                    {
                        bool checkSame = false;
                        checkSame = _manager.CheckSameOrg40(obj);
                        if (checkSame == false)
                        {
                            kq = _manager.UpdateDateOrg39BaseCurrentID(obj);
                            if (kq != 0 && kq != -1)
                            {
                                btn登録.Text = "登録";
                                ClearTextPage();
                                ShowDataPageLoadUpdateMode(obj.社員ID.ToString());
                                ViewState["IdCurrentOrg40"] = "";
                                ViewState["IdCurrentOutputOrg40Update"] = IdCurrent;
                                ViewState["FirstRowUpdateOrg40"] = false;
                            }
                        }
                        else
                        {
                            string MessageCode = GetError("ER00009");
                            Page.ClientScript.RegisterStartupScript(typeof(Page), "Same 2", "alert('" + MessageCode + "');", true);
                        }
                    }
                }
                else if (boolFirstRowUpdate == "False" || boolFirstRowUpdate == "false")
                {
                    if (ViewState["CountingSubmitOrg40"].ToString() == Session["CountingSubmitOrg40"].ToString())
                    {
                        // Truong hop insert them moi
                        int kq = 0;
                        bool checkSame = false;
                        checkSame = _manager.CheckSameOrg40(obj);
                        if (checkSame == false)
                        {
                            int intIdCurrent = 0;
                            kq = _manager.InsertDataOrg40(obj, out intIdCurrent);
                            if (kq != 0 && intIdCurrent != 0)
                            {
                                ViewState["IdCurrentOrg40"] = "";
                                ViewState["IdCurrentOutputOrg40"] = intIdCurrent.ToString();
                                ClearTextPage();
                                ShowDataPageLoadUpdateMode(obj.社員ID.ToString());
                                Session["CountingSubmitOrg40"] = Server.UrlEncode(System.DateTime.Now.ToString());

                            }
                        }
                        else
                        {
                            string MessageCode = GetError("ER00009");
                            //ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('" + MessageCode + "');</script>");
                            //return;
                            Page.ClientScript.RegisterStartupScript(Page.GetType(), "Same 2", "alert('" + MessageCode + "');", true);
                        }
                    }
                    else
                    {
                        ClearTextPage();
                        ShowDataPageLoadUpdateMode(obj.社員ID.ToString());
                    }
                
                }
            }

            if (IdCurrent != "")
            {
                // Truong hop cap nhat lai dong tuong ung
                int kq = 0;
                bool checkExist = false;
                obj.ID = Int32.Parse(IdCurrent);

                checkExist = _manager.CheckExistsOrg40(obj);

                if (checkExist == true)
                {
                    kq = _manager.UpdateDateOrg39BaseCurrentID(obj);
                    if (kq != 0 && kq != -1)
                    {
                        btn登録.Text = "登録";
                        ClearTextPage();
                        ShowDataPageLoadUpdateMode(obj.社員ID.ToString());
                        ViewState["IdCurrentOrg40"] = "";
                        ViewState["IdCurrentOutputOrg40Update"] = IdCurrent;
                    }
                }
                else
                {
                    bool checkSame = false;
                    checkSame = _manager.CheckSameOrg40(obj);
                    if (checkSame == false)
                    {
                        kq = _manager.UpdateDateOrg39BaseCurrentID(obj);
                        if (kq != 0 && kq != -1)
                        {
                            btn登録.Text = "登録";
                            ClearTextPage();
                            ShowDataPageLoadUpdateMode(obj.社員ID.ToString());
                            ViewState["IdCurrentOrg40"] = "";
                            ViewState["IdCurrentOutputOrg40Update"] = IdCurrent;
                        }
                    }
                    else
                    {
                        string MessageCode = GetError("ER00009");
                        Page.ClientScript.RegisterStartupScript(typeof(Page), "Same 2", "alert('" + MessageCode + "');", true);
                    }
                }
            }
        }

    }

    /// <summary>
    /// Hien thi du lieu rong cho Gridview
    /// </summary>
    /// <param name="grv"></param>
    /// <param name="strTableHeader"></param>
    /// <param name="strEmpty"></param>
    public void ShowGridViewNotClassEmpty(GridView grv, string strTableHeader, string strEmpty)
    {
        DataTable dt = new DataTable();
        string[] arrColumnNames = strTableHeader.Split(',');
        foreach (string str in arrColumnNames)
        {
            dt.Columns.Add(str);
        }
        grv.ShowFooter = false;
        DataRow r = dt.NewRow();
        dt.Rows.InsertAt(r, 0);
        grv.DataSource = dt;
        grv.DataBind();
        grv.Rows[0].Cells.Clear();
        TableCell cell = new TableCell();
        cell.ColumnSpan = grv.Columns.Count + 1;
        cell.Text = strEmpty;
        grv.Rows[0].Cells.Add(cell);

    }

    # region Khong Su Dung
    //protected void btn登録_Click(object sender, EventArgs e)
    //{
    //    if ((txt_実際開始日.Text == "" && txt_発令開始日.Text == "") || txt_発令開始日.Text != "" && txt_実際開始日.Text != "")
    //    {
    //        雇用情報 obj = new 雇用情報();

    //        obj.廃止区分 = 0;
    //        if (ddl_雇用区分.SelectedValue.ToString() != "-11")
    //        {
    //            obj.雇用区分_s = ddl_雇用区分.SelectedValue.ToString();
    //            obj.雇用区分名 = ddl_雇用区分.SelectedItem.Text.ToString();
    //        }
    //        if (txt_発令開始日.Text != "")
    //        {
    //            DateTime d1 = DateTime.Parse(txt_発令開始日.Text);
    //            obj.発令開始日 = d1;
    //        }
    //        if (txt_実際開始日.Text != "")
    //        {
    //            DateTime d2 = DateTime.Parse(txt_実際開始日.Text);
    //            obj.実際開始日 = d2;
    //        }
    //        obj.社員ID = Int32.Parse(Session["社員ID"].ToString());

    //        if (Session["CountingSubmitOrg40"].ToString() == ViewState["CountingSubmitOrg40"].ToString())
    //        {
    //            int kq = new 雇用情報Manager().InsertPartial(obj);
    //            try
    //            {
    //                if (kq != 0 && kq != -1)
    //                {
    //                    ClearTextPage();
    //                    Session["CountingSubmitOrg40"] = Server.UrlEncode(System.DateTime.Now.ToString());
    //                    Response.Redirect("frmO_EmpDegreeByCompInput.aspx", false);
    //                }
    //            }
    //            catch (Exception ex)
    //            {
    //                ex.Message.ToString();
    //            }
    //        }
    //    }

    //}
    # endregion
    protected void grv_human_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Load"))
        {
            int pagecurrent = Int32.Parse(ViewState["indexPageOrg40"].ToString());
            int index;
            if (pagecurrent == 0)
                index = Int32.Parse(e.CommandArgument.ToString());
            else
                index = Convert.ToInt32(e.CommandArgument) + pagecurrent * 10;
            if (index == -1) return;

            string PageCurrentMode = Session["PageCurrentOrg39Mode"] != null ? Session["PageCurrentOrg39Mode"].ToString() : "";

            if (PageCurrentMode == "1" || PageCurrentMode=="3")
            {
                DataTable dt = (DataTable)ViewState["TableInsertOrg40"];
                if(dt != null && dt.Rows.Count>0)
                {
                    string temp1 = dt.Rows[index]["雇用区分"].ToString();
                    string temp2 = dt.Rows[index]["発令開始日"].ToString();
                    string temp3 = dt.Rows[index]["実際開始日"].ToString();
                    string _ID = dt.Rows[index]["ID"].ToString();
                    if (temp1 != "")
                    {
                        if (temp1 == "0")
                            temp1 = "00";
                        ListItem lst = ddl_雇用区分.Items.FindByValue(temp1);
                        ddl_雇用区分.SelectedIndex = ddl_雇用区分.Items.IndexOf(lst);
                    }

                    if (temp3 != "")
                    {
                        txt_実際開始日.Text = temp3.Substring(0, 10);
                    }

                    if (temp2 != "")
                    {
                        txt_発令開始日.Text = temp2.Substring(0, 10);
                    }
                    ViewState["indexOrg40"] = index;
                    ViewState["IdCurrentOrg40"] = _ID;
                    btn登録.Text = "更新";
                }
                else
                {
                    // Hien thi GridView rong
                    string header = "ID,雇用区分,発令開始日,実際開始日";
                    string phraseEmpty = "データーがありません。";
                    ShowGridViewNotClassEmpty(grv_human, header, phraseEmpty);
                  
                }
            }

            if (PageCurrentMode == "2" || PageCurrentMode == "4")
            {
                DataTable dt = (DataTable)ViewState["TableUpdateOrg40"];
                if (dt != null && dt.Rows.Count > 0)
                {
                    string temp1 = dt.Rows[index]["雇用区分"].ToString();
                    string temp2 = dt.Rows[index]["発令開始日"].ToString();
                    string temp3 = dt.Rows[index]["実際開始日"].ToString();
                    string _ID = dt.Rows[index]["ID"].ToString();
                    if (temp1 != "")
                    {
                        if (temp1 == "0")
                            temp1 = "00";
                        ListItem lst = ddl_雇用区分.Items.FindByValue(temp1);
                        ddl_雇用区分.SelectedIndex = ddl_雇用区分.Items.IndexOf(lst);
                    }

                    if (temp3 != "")
                    {
                        txt_実際開始日.Text = temp3.Substring(0, 10);
                    }

                    if (temp2 != "")
                    {
                        txt_発令開始日.Text = temp2.Substring(0, 10);
                    }
                    ViewState["indexOrg40"] = index;
                    ViewState["IdCurrentOrg40"] = _ID;
                    btn登録.Text = "更新";
                    ViewState["FirstRowUpdateOrg40"] = false;
                }
                else
                {
                    // Hien thi GridView rong
                    string header = "ID,雇用区分,発令開始日,実際開始日";
                    string phraseEmpty = "データーがありません。";
                    string _社員ID = Request.QueryString["id"].ToString();
                    ShowGridViewNotClassEmpty(grv_human, header, phraseEmpty);
                    

                }
            }

        }
    }

    protected void grv_human_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onclick", "javascript:__doPostBack('ctl00$ContentPlaceHolder1$grv_human','Load$" + e.Row.RowIndex + "')");
        }
    }
    
    protected void grv_human_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
       
    }

    protected void grv_human_PreRender(object sender, EventArgs e)
    {
        // To mau truong hop Insert
        string IdCurrentOutput = ViewState["IdCurrentOutputOrg40"] != null ? ViewState["IdCurrentOutputOrg40"].ToString() : "";
        if (IdCurrentOutput != "")
        {
            for (int i = 0; i < grv_human.Rows.Count; i++)
            {
                string key = grv_human.DataKeys[i].Value.ToString();
                if (key.Equals(IdCurrentOutput))
                {
                    grv_human.Rows[i].CssClass = "insert";
                    ViewState["IdCurrentOutputOrg40"] = "";
                    break;
                }
            }
        }
        // To mau truong hop Update
        string IdCurrentOutputUpdate = ViewState["IdCurrentOutputOrg40Update"] != null ? ViewState["IdCurrentOutputOrg40Update"].ToString() : "";
        if (IdCurrentOutputUpdate != "")
        {
            for (int i = 0; i < grv_human.Rows.Count; i++)
            {
                string key = grv_human.DataKeys[i].Value.ToString();
                if (key.Equals(IdCurrentOutputUpdate))
                {
                    grv_human.Rows[i].CssClass = "update";
                    ViewState["IdCurrentOutputOrg40Update"] = "";
                    break;
                }
            }
        }
    }
    
    protected void grv_human_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
         grv_human.PageIndex =  e.NewPageIndex;
         ViewState["indexPageOrg40"] = e.NewPageIndex;
      
        string PageCurrentMode = Session["PageCurrentOrg39Mode"] != null ? Session["PageCurrentOrg39Mode"].ToString() : "";
        if (PageCurrentMode == "1")
        {
            if (Request.QueryString["id"] != null)
            {
                string _社員ID = Request.QueryString["id"].ToString();
                ShowDataPageFirstLoadInsertMode(_社員ID);
            }
        }

        if (PageCurrentMode == "3")
        {
            string _社員ID = Session["社員ID"] != null ? Session["社員ID"].ToString() : "";
            ShowDataPageFirstLoadInsertMode(_社員ID);
        }

        if (PageCurrentMode == "2")
        {
            if (Request.QueryString["id"] != null && Request.QueryString["id2"] != null)
            {
                string _社員ID = Request.QueryString["id"].ToString();
                string _ID = Request.QueryString["id2"].ToString();
                ShowDataPageFirstLoadInsertMode(_社員ID);
            }
        }

        if (PageCurrentMode == "4")
        {
            if (Request.QueryString["id"] != null && Request.QueryString["id2"] != null)
            {
                string _社員ID = Request.QueryString["id"].ToString();
                string _ID = Request.QueryString["id2"].ToString();
                ShowDataPageFirstLoadInsertMode(_社員ID);
            }
        }
    }

    public string ConvertNumberTypeToChar(object source)
    {
        if (source == null || source.ToString() == "")
            return "";
        string temp = source.ToString();
        if (temp == "00" || temp == "0")
            return "役員";
        if (temp == "10")
            return "社員";
        if (temp == "20")
            return "契約社員";
        if (temp == "21")
            return "契約（パート）";
        if (temp == "22")
            return "契約（アルバイト）";
        if (temp == "30")
            return "派遣社員";
        if (temp == "90")
            return "その他";
        ListItem lst = ddl_雇用区分.Items.FindByValue(temp);
        if(lst != null)
            return lst.Text;
        return "";
    }
}